package com.yilin.platform.base_core.interceptor;


import com.yilin.platform.base_core.application.UserUtil;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import com.yilin.platform.base_core.components.FptClient;
import com.yilin.platform.entity.user.deserialize.Account;
import com.yilin.platform.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 微服务内部鉴权控制器
 */
@Configuration
public class LoginInterceptor implements  HandlerInterceptor  {
    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Lazy
    @Autowired
    IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            SkipLoginVerify skipLoginVerify = handlerMethod.getMethodAnnotation(SkipLoginVerify.class);
            if (skipLoginVerify == null) {
                String tokenID = request.getHeader("token");
                if (StringUtil.isEmpty(tokenID)) return responseErr(response,401,"您未登录！");
                if (UserUtil.getLoginUser(tokenID) == null){
                    // 易林请求自动登录，只要是易林的请求均自动登录鉴权
                    Account yilinLoginUser = userService.getYilinLoginUser(tokenID);
                    if (yilinLoginUser==null) return  responseErr(response,401,"登录失效");
                    UserUtil.saveLoginUser(tokenID, yilinLoginUser);
                }
                return true;
            }
        }
        return true;
    }


    //返回前台数据
    private boolean responseErr(HttpServletResponse response, Integer code, String msg) {
        try {
            Map<String, Object> returnData = new HashMap<>();
            response.setCharacterEncoding("UTF-8");//设置字符集为'UTF-8'
            response.setContentType("application/json");//设置格式为text/json 
            returnData.put("success", false);
            returnData.put("msg", msg);
            returnData.put("code", code);
            PrintWriter write = response.getWriter();
            write.write(JsonUtil.objectToJson(returnData));
            write.flush();
            write.close();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


}
